package com.kung.qvs.ui.main.fragment.manage;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.entity.ProductTypeBean;
import com.kung.qvs.entity.SpinnerItemData;
import com.kung.qvs.utils.Constants;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.binding.viewadapter.spinner.IKeyAndValue;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class FragProductAddModel extends BaseViewModel<JtRepository> {
    public FragProductAddModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    public ObservableField<Boolean> mIsUpdate = new ObservableField<>(true);    //是否为新增
    public ObservableField<String> mProductId = new ObservableField<>("");    //产品编号
    public ObservableField<String> mProductName = new ObservableField<>("");    //产品名称
    public ObservableField<String> mParentId = new ObservableField<>("");    //产品类型
    public ObservableField<String> mProductWeight = new ObservableField<>("");    //产品标准重量
    //转换值
    public ObservableField<String> mConvertValue = new ObservableField<>("");    //产品转换值
    public ObservableField<String> mProductRemark = new ObservableField<>("");    //产品规格

    public List<IKeyAndValue> productTypeDatas = new ArrayList<>();

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent eventToLastPage = new SingleLiveEvent<>();
        public SingleLiveEvent eventSaveProduct = new SingleLiveEvent();
    }

    public BindingCommand onCommandBack = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //返回
            uc.eventToLastPage.call();
        }
    });

    //保存
    public BindingCommand onCommandSave = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventSaveProduct.call();
        }
    });

    //类型选择的监听
    public BindingCommand<IKeyAndValue> onSelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            mParentId.set(iKeyAndValue.getValue());
        }
    });

    public int funLoadProductTypes(List<ProductTypeBean> list) {
        productTypeDatas = new ArrayList<>();
        int index = 0;
        int select = 0;
        for (ProductTypeBean bean : list) {
            if (bean.getProductId().equals(mParentId.get())) {
                select = index;
            }
            index++;
            productTypeDatas.add(new SpinnerItemData(bean.getProductName(), bean.getProductId()));
        }
        return select;
    }

    public void funSaveProduct() {
        if (mProductId.get().isEmpty()) {
            ToastUtils.showShort("请输入产品编号");
            return;
        }

        if (mProductName.get().isEmpty()) {
            ToastUtils.showShort("请输入产品名称");
            return;
        }
        if (mParentId.get().isEmpty()) {
            ToastUtils.showShort("请选择产品类型");
            return;
        }
        if (mProductWeight.get().isEmpty()) {
            ToastUtils.showShort("请输入产品标准重量");
            return;
        }
//        if (mConvertValue.get().isEmpty()) {
//            ToastUtils.showShort("请输入产品转换值");
//            return;
//        }
        if (mProductRemark.get().isEmpty()) {
            ToastUtils.showShort("请输入产品规格");
            return;
        }

        if (mIsUpdate.get()) {
            model.reqUpdateProductBean("", model.getEquipmentNo(), mProductId.get(), mParentId.get(), mProductName.get(), mProductWeight.get(), mConvertValue.get(), mProductRemark.get())
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .timeout(Constants.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在保存数据...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResultBean<Integer>>() {
                        @Override
                        public void onNext(BaseResultBean<Integer> response) {
                            //请求成功
                            if (response.isSuccess()) {
                                //数据插入本地，并根据id排序查询。已被无网络情况使用
                                uc.eventToLastPage.call();
                            } else {
                                //code错误时也可以定义Observable回调到View层去处理
                                ToastUtils.showShort("保存失败，产品编号或名称已存在");
                            }
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(((ResponseThrowable) throwable).message);
                                //token失效，重新登录
//                            finish();
                                //如果无网络，使用本地缓存垃圾分类
                            }
                        }

                        @Override
                        public void onComplete() {
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        } else {
            model.reqAddProductBean("", model.getEquipmentNo(), mProductId.get(), mParentId.get(), mProductName.get(), mProductWeight.get(), mConvertValue.get(), mProductRemark.get())
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .timeout(Constants.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在保存数据...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResultBean<Integer>>() {
                        @Override
                        public void onNext(BaseResultBean<Integer> response) {
                            //请求成功
                            if (response.isSuccess()) {
                                //数据插入本地，并根据id排序查询。已被无网络情况使用
                                uc.eventToLastPage.call();
                            } else {
                                //code错误时也可以定义Observable回调到View层去处理
                                ToastUtils.showShort("保存失败，产品编号或名称已存在");
                            }
                        }

                        @Override
                        public void onError(Throwable throwable) {
                            //关闭对话框
                            dismissDialog();
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(((ResponseThrowable) throwable).message);
                                //token失效，重新登录
//                            finish();
                                //如果无网络，使用本地缓存垃圾分类
                            }
                        }

                        @Override
                        public void onComplete() {
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        }
    }

}
